package com.recycle.controller.login;

import com.google.code.kaptcha.Producer;
import com.recycle.common.constant.CacheConstants;
import com.recycle.common.result.GraceJSONResult;
import com.recycle.common.utils.Base64;
import com.recycle.common.utils.IdUtils;
import com.recycle.common.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

/**
 * 验证码操作处理
 * 
 * @author ruoyi
 */
@RestController
public class CaptchaController
{
    @Resource(name = "captchaProducer")
    Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    Producer captchaProducerMath;

    @Autowired
    RedisOperator redisOperator;
    
    // 验证码类型
    @Value("${captcha.type}")
    String captchaType;

    // 验证码开关
    @Value("${captcha.enabled}")
    String captchaEnabled;

    // 验证码有效期（分钟）
    @Value("${captcha.expiration}")
    String expiration;


    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public GraceJSONResult getCode() throws IOException
    {
        GraceJSONResult result = GraceJSONResult.ok();
        if (!"false".equals(captchaEnabled))
        {
            return result;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr, code = null;
        BufferedImage image = null;

        // 生成验证码
        if ("math".equals(captchaType))
        {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        else if ("char".equals(captchaType))
        {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisOperator.set(verifyKey, code, Long.parseLong(expiration) * 60);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try
        {
            assert image != null;
            ImageIO.write(image, "jpg", os);
        }
        catch (IOException e)
        {
            return GraceJSONResult.errorMsg(e.getMessage());
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        result.setData(map);
        return result;
    }
}
